<?php
class DBConfig
{
    // mysql 主机列表, 读,写分别配置
    // DB::getConnect() 会随机查找可用host, 直到找到可用的
    // utf8mb4: 支持emoji表情的字符集, 最新版的mysql已设为默认字符集
    public static $hosts = array();
    
    //table info
    //虚拟表名 => 虚拟主机名, 数据库名, 表名
    //将所有表在此备案, 方便管理, 其中虚拟主机名对应self::$hosts 键名, 如 default
    public static $TableInfo = array(
        'user'             => 'default, test, user',
        'role'             => 'default, test, role',
        'role_bind'        => 'default, test, role_bind',
        
        'global_id'         => 'default, test, global_id',
        'gid'               => 'default, test, global_id',

        'test_(\d+)_(\d+)' => 'default, test, test_$1_$2',

        //db队列
        'queue_message' => 'default, queue, queue_message',
        'queue_consumer' => 'default, queue, queue_consumer',
        'queue_handle' => 'default, queue, queue_handle',
    );

    public static function getJsonConfig()
    {
        $realPath = realpath(MYSQL_HOST_FILE);
        if ($realPath && file_exists($realPath)) {
            $str = file_get_contents($realPath);
            self::$hosts = json_decode($str, true);
        } else {
            throw new Exception('数据库配置文件未找到!');
        }
    }

    public static function init()
    {
        if (empty(self::$hosts)) {
            self::getJsonConfig();
        }
        //FileLog::ini('error')->info(self::$hosts);
    }

    //获取所有的主机虚拟名称
    public static function getAllHostsName()
    {
        return array_keys(self::$hosts);
    }

    //获取某个DB主机的配置信息
    public static function getHostInfo($host)
    {
        return reset(self::$hosts[$host]['read']);
    }

}

/*
 dbConfig.json配置解析后格式如下:
array(
        'default' => array(
            'write' => array(
                array('host' => '127.0.0.1', 'username' => '', 'password' => '', 'port' => 3306, 'charset' => 'utf8'),
                // 其他可用主机
            ),
            'read' => array(
                array('host' => '127.0.0.1', 'username' => '', 'password' => '', 'port' => 3306, 'charset' => 'utf8'),
                array('host' => '127.0.0.2', 'username' => '', 'password' => '', 'port' => 3306, 'charset' => 'utf8'),
                // 其他可用主机
            )
        ),

        'other' => array(
            'write' => array(),
            'read' => array()
        )
    );
 */